const QQMapWX = require("/common/javascript/qqmap-wx-jssdk.min.js");
// const mtaAnalysis = require("/common/javascript/mta_analysis.js");

App({
  onLaunch: function() {
    //隐藏系统tabbar
    wx.hideTabBar();
    this.getSystemInfo();
    this.globalData.yardId = wx.getStorageSync("yardId");
    this.globalData.roomId = wx.getStorageSync("roomId");
    this.globalData.areaCode = wx.getStorageSync("areaCode");
    //获取个人信息
    this.getUserInfo().then(result => {
      this.globalData.userInfo = result.data;
      console.error(result.data)
    });
    //检查更新
    const updateManager = wx.getUpdateManager()
    updateManager.onCheckForUpdate(function(res) {

    });
    updateManager.onUpdateReady(function() {
      wx.showModal({
        title: '更新提示',
        showCancel: false,
        content: '新版本已经准备好，请立即更新小程序',
        success: function(res) {
          if (res.confirm) {
            updateManager.applyUpdate();
          }
        }
      })
    });
    updateManager.onUpdateFailed(function() {

    });
  },
  globalData: {
    appType: 0,
    appTitle: '猛追湾街道',
    url: "https://www.xinwangzn.com/api", //请求数据地址(线上)
    // url: "http://10.0.0.67:82", //请求数据地址(本地)
    // url:"http://10.0.0.234:8080",
    //urlMicro: "http://10.0.0.67:60889",//本地微服务
    urlMicro: "http://xinwangzn.com:85/api-conference", //线上微服务
    //urlFace: "https://www.aierbanjia.cn:89", //头像检测是否合格的地址(线上)
    //urlIdcard: "https://www.aierbanjia.cn:7788", //身份证验证接口
    //urlFace: "http://10.0.0.203:81", //头像检测是否合格的地址(本地)
    urlImage: "/mine/uploading", //上传图片地址
    //showImage: "http://119.84.46.242:6655/", //显示图片地址
    //isReplaceImgIp: false, //是否替换图片ip （true代表替换 端口7777换地址 8311不需要换）
    theme: {
      themeColor: ["#659FB0", "#73C4D6", "#D2DCE2", "#D7AB8C"], //主题颜色(从主题色->辅助色)
      titleColor: ["#7D8561", "#FAA966", "#3c3c3c", "#C8B9A4"], //标题颜色(从标题->分割线)
      titleSize: [40, 36, 32, 30], //标题字体大小(从大字体->小字体)
      contentSize: [30, 28, 26], //内容字体大小(从大字体->小字体)
      commentSize: 22, //注释字体大小
      tabIconColor: "#409eff ", //tab选中图标的颜色
      tabIconSelectedColor: "#D8D8D8", //tab未选中的图标颜色
      elPadding: [24, 24], //页面边距(从上下->左右距离)
      elSpecialPadding: [15, 60], //特殊页面边距(登录页面、)
      btnHeight: [100, 60], //按钮高度(从大按钮->小按钮)
      btnTextSize: [40, 30], //按钮文字大小(从大字体->小字体)
      editBackgroundColor: "#F6F6F7"
    },
    accessToken: "", //用于判断是否登录
    refreshToken: "", //用于token过期刷新accessToken
    unitCode: "86.001.001.001.001.009.003", //单位编码（本地白莲社区86.001.001.001.001.003.001）（线上86.001.001.001.001.010.002）
    qqMapWx: new QQMapWX({
      key: "RSTBZ-OBURR-FZNWJ-WS7IX-SQANS-DAB56", //腾讯地图key
    }), //初始化腾讯地图
    pageNumber: 1,
    pageSize: 10,
    pageTotalNumber: 0, //总页数
    userInfo: {}, //用户个人信息
    wxUserInfo: {},
    mobileRegexp: /^1[345789]\d{9}$/,
    idCardRegexp: /(^\d{15}$)|(^\d{17}([0-9]|X|x)$)/,
    yardId: "", //院落id
    parentAreaCode: "86.51.01.08.09.04", //望平社区(本地86.51.01.08.03.01)（线上86.51.01.08.10.02）
    areaCode: "", //暂时未用
    roomId: "", //房间id
    systemInfo: null,//客户端设备信息
    tabBar: {
      "color": "#838685", 
      "selectedColor": "#409eff",
      "backgroundColor": "#ffffff",
      "borderStyle": "black",
      "list": [{
          "pagePath": "/pages/index/index",
          "iconPath": "icon/home.png",
          "selectedIconPath": "icon/home_selected.png",
          "text": "首页"
      },
        {
          "pagePath": "/pages/mine/community_worker/handle_to_unit/handle_to_unit",
          "iconPath": "icon/report.png",
          "selectedIconPath": "icon/report_selected.png",
          "text": "便民电话"
        }, 
        {
          "isSpecial": true,
          "pagePath": "/pages/event/event_report/event_report_small_type/event_report_small_type",
          "iconPath": "icon/icon_release.png",
          "text": "随手报"
        },
        {
          "pagePath": "/pages/index/service_more/service_more",
          "iconPath": "icon/shop.png",
          "selectedIconPath": "icon/shop_selected.png",
          "text": "社区服务"
        },
        {
          "pagePath": "/pages/mine/mine",
          "iconPath": "icon/my.png",
          "selectedIconPath": "icon/my_selected.png",
          "text": "我的"
        }
      ]
    }
  },
  editTabbar: function () {
    //隐藏系统tabbar
    wx.hideTabBar()
    let tabbar = this.globalData.tabBar;
    let currentPages = getCurrentPages();
    let _this = currentPages[currentPages.length - 1];
    let pagePath = _this.route;
    (pagePath.indexOf('/') != 0) && (pagePath = '/' + pagePath);
    for (let i in tabbar.list) {
      tabbar.list[i].selected = false;
      (tabbar.list[i].pagePath == pagePath) && (tabbar.list[i].selected = true);
    }
    _this.setData({
      tabbar: tabbar
    });
  },
  getSystemInfo: function () {
    wx.getSystemInfo({
      success: (res)=> {
        this.globalData.systemInfo = res;
      }
    });
  },
  /**
   * 封装所有方法
   */
  /*无等待匡出现get方法*/
  wxGetRequest: function(urlStr, data) {
    let promise = new Promise((resolve, reject) => {
      wx.getNetworkType({
        success: res => {
          if (res.networkType != "none") {
            if (data === undefined) {
              data = {};
            }
            console.log("<!--------[" + urlStr + "]---------------------------------------------------------------");
            console.log("地址: " + urlStr);
            try {
              var dataStr = JSON.stringify(data);
              console.log("参数: " + dataStr);
            } catch (e) {

            }
            wx.request({
              url: this.globalData.url + urlStr,
              data: data,
              header: {
                'content-type': 'application/x-www-form-urlencoded',
                'Authorization': this.globalData.accessToken
              },
              method: 'GET',
              dataType: 'json',
              responseType: 'text',
              success: res => {
                console.log("响应: " + JSON.stringify(res));
                console.log("----------[" + JSON.stringify(urlStr) + "]--------------------------------------------------------------->");
                if (res.statusCode == 200) {
                  try {
                    resolve(res);
                  } catch (e) {

                  }
                } else {
                  if (res.statusCode == 401) {
                    if (urlStr == "/app-org/v1/authorization/user") {
                      this.alert("提示", res.data.message);
                      return;
                    } else {
                      this.wxRefreshToken().then(result => {
                        this.wxGetRequest(urlStr, data);
                      });
                      return;
                    }
                  } else if (res.statusCode == 400 || res.statusCode == 500) {
                    this.alert("提示", res.data.message);
                    return;
                  }
                }
              },
              fail: res => {
                setTimeout(function() {
                  wx.showToast({
                    title: "服务器繁忙!",
                    image: "/common/image/warning.png",
                  });
                  reject();
                }, 1000);
              },
              complete: res => {
                wx.hideLoading();
                wx.stopPullDownRefresh();
              }
            });
          } else {
            this.alert("提示", "网络未连接!");
          }
        }
      });
    });
    return promise;
  },
  /*无等待匡出现post方法*/
  wxPostRequest: function(urlStr, data) {
    let promise = new Promise((resolve, reject) => {
      wx.getNetworkType({
        success: res => {
          if (res.networkType != "none") {
            if (data === undefined) {
              data = {};
            }
            console.log("<!--------[" + urlStr + "]---------------------------------------------------------------");
            console.log("地址: " + urlStr);
            try {
              var dataStr = JSON.stringify(data);
              console.log("参数: " + dataStr);
            } catch (e) {

            }
            wx.request({
              url: this.globalData.url + urlStr,
              data: data,
              header: {
                'content-type': 'application/x-www-form-urlencoded',
                'Authorization': this.globalData.accessToken
              },
              method: 'POST',
              dataType: 'json',
              responseType: 'text',
              success: res => {
                console.log("响应: " + JSON.stringify(res));
                console.log("----------[" + JSON.stringify(urlStr) + "]--------------------------------------------------------------->");
                if (res.statusCode == 200) {
                  try {
                    resolve(res);
                  } catch (e) {

                  }
                } else {
                  if (res.statusCode == 401) {
                    if (urlStr == "/app-org/v1/authorization/user") {
                      this.alert("提示", res.data.message);
                      return;
                    } else {
                      this.wxRefreshToken().then(result => {
                        this.wxPostRequest(urlStr, data);
                      });
                      return;
                    }
                  } else if (res.statusCode == 400 || res.statusCode == 500 || res.statusCode == 502 || res.statusCode == 412) {
                    if (urlStr == "/api-face/v1/face/auth" || urlStr == "/api-face/v1/face/unauth") {
                      reject(res);
                      return;
                    } else {
                      this.alert("提示", res.data.message);
                      return;
                    }
                  }
                }
              },
              fail: res => {
                setTimeout(function() {
                  wx.showToast({
                    title: "服务器繁忙!",
                    image: "/common/image/warning.png",
                  });
                  reject(res);
                }, 1000);
              },
              complete: res => {
                wx.hideLoading();
                wx.stopPullDownRefresh();
              }
            });
          } else {
            this.alert("提示", "网络未连接!");
          }
        }
      });
    });
    return promise;
  },
  /*无等待匡出现put方法*/
  wxPutRequest: function(urlStr, data) {
    let promise = new Promise((resolve, reject) => {
      wx.getNetworkType({
        success: res => {
          if (res.networkType != "none") {
            if (data === undefined) {
              data = {};
            }
            console.log("<!--------[" + urlStr + "]---------------------------------------------------------------");
            console.log("地址: " + urlStr);
            try {
              var dataStr = JSON.stringify(data);
              console.log("参数: " + dataStr);
            } catch (e) {

            }
            wx.request({
              url: this.globalData.url + urlStr,
              data: data,
              header: {
                'content-type': 'application/x-www-form-urlencoded',
                'Authorization': this.globalData.accessToken
              },
              method: 'PUT',
              dataType: 'json',
              responseType: 'text',
              success: res => {
                console.log("响应: " + JSON.stringify(res));
                console.log("----------[" + JSON.stringify(urlStr) + "]--------------------------------------------------------------->");
                if (res.statusCode == 200) {
                  try {
                    resolve(res);
                  } catch (e) {

                  }
                } else {
                  if (res.statusCode == 401) {
                    if (urlStr == "/app-org/v1/authorization/user") {
                      this.alert("提示", res.data.message);
                      return;
                    } else {
                      this.wxRefreshToken().then(result => {
                        this.wxPutRequest();
                      });
                      return;
                    }
                  } else if (res.statusCode == 400 || res.statusCode == 500) {
                    this.alert("提示", res.data.message);
                    return;
                  }
                }
              },
              fail: res => {
                setTimeout(function() {
                  wx.showToast({
                    title: "服务器繁忙!",
                    image: "/common/image/warning.png",
                  });
                  reject();
                }, 1000);
              },
              complete: res => {
                wx.hideLoading();
              }
            });
          } else {
            this.alert("提示", "网络未连接!");
          }
        }
      });
    });
    return promise;
  },
  /*无等待匡出现Delete方法*/
  wxDeleteRequest: function(urlStr, data) {
    let promise = new Promise((resolve, reject) => {
      wx.getNetworkType({
        success: res => {
          if (res.networkType != "none") {
            if (data === undefined) {
              data = {};
            }
            console.log("<!--------[" + urlStr + "]---------------------------------------------------------------");
            console.log("地址: " + urlStr);
            try {
              var dataStr = JSON.stringify(data);
              console.log("参数: " + dataStr);
            } catch (e) {

            }
            wx.request({
              url: this.globalData.url + urlStr,
              data: data,
              header: {
                'content-type': 'application/x-www-form-urlencoded',
                'Authorization': this.globalData.accessToken
              },
              method: 'DELETE',
              dataType: 'json',
              responseType: 'text',
              success: res => {
                console.log("响应: " + JSON.stringify(res));
                console.log("----------[" + JSON.stringify(urlStr) + "]--------------------------------------------------------------->");
                if (res.statusCode == 200) {
                  try {
                    resolve(res);
                  } catch (e) {

                  }
                } else {
                  if (res.statusCode == 401) {
                    if (urlStr == "/app-org/v1/authorization/user") {
                      this.alert("提示", res.data.message);
                      return;
                    } else {
                      this.wxRefreshToken().then(result => {
                        this.wxDeleteRequest(urlStr, data);
                      });
                      return;
                    }
                  } else if (res.statusCode == 400 || res.statusCode == 500) {
                    if (urlStr == "/api-face/v1/face/auth" || urlStr == "/api-face/v1/face/unauth") {
                      reject(res);
                      return;
                    } else {
                      this.alert("提示", res.data.message);
                      return;
                    }
                  }
                }
              },
              fail: res => {
                reject(res);
                setTimeout(function() {
                  wx.showToast({
                    title: "服务器繁忙!",
                    image: "/common/image/warning.png",
                  });
                }, 1000);
              },
              complete: res => {

                wx.hideLoading();
                wx.stopPullDownRefresh();
              }
            });
          } else {
            this.alert("提示", "网络未连接!");
          }
        }
      });
    });
    return promise;
  },
  /**
   * 过期刷新token
   */
  wxRefreshToken: function() {
    let promise = new Promise((resolve, reject) => {
      wx.getNetworkType({
        success: res => {
          if (res.networkType != "none") {
            wx.request({
              url: this.globalData.url + "/app-org/v1/authorization/token",
              data: {
                refresh_token: this.globalData.refreshToken
              },
              header: {
                'content-type': 'application/x-www-form-urlencoded',
                "Authorization": this.globalData.accessToken
              },
              method: 'PUT',
              dataType: 'json',
              responseType: 'text',
              success: result => {
                if (result.statusCode == 200) {
                  try {
                    wx.setStorageSync('accessToken', result.data.access_token);
                    wx.setStorageSync('refreshToken', result.data.refresh_token);
                  } catch (e) {}
                  this.globalData.accessToken = result.data.access_token;
                  this.globalData.refreshToken = result.data.refresh_token;
                  resolve();
                } else {
                  if (result.statusCode == 400 || result.statusCode == 500) {
                    this.alert("提示", result.data.message);
                    return;
                  } else if (result.statusCode == 401) {
                    wx.navigateTo({
                      url: '/pages/mine/login/login',
                    });
                    return;
                  }
                }
              },
              fail: res => {
                setTimeout(function() {
                  wx.showToast({
                    title: "服务器繁忙!",
                    image: "/common/image/warning.png",
                  });
                  reject();
                }, 1000);
              },
              complete: res => {

                wx.hideLoading();
              }
            });
          } else {
            this.alert("提示", "网络未连接!");
          }
        }
      });
    });
    return promise;
  },
  /**
   * 原生上传图片
   */
  uploadFile: function(filePath, progressUpdate) {
    let promise = new Promise((resolve, reject) => {
      let uploadTask = wx.uploadFile({
        url: this.globalData.url + this.globalData.urlImage,
        filePath: filePath,
        name: "file",
        header: {
          "Authorization": this.globalData.accessToken
        },
        formData: {
          savePath: "/applets/photo",
        },
        success: res => {
          console.error(res)
          resolve(JSON.parse(res.data));
        },
        fail: res => {
          reject(res);
        },
        complete: res => {
          console.log(res)
          wx.hideLoading();
        }
      });
      uploadTask.onProgressUpdate((res) => {
        progressUpdate(res);
        // console.log('上传进度', res.progress)
        // console.log('已经上传的数据长度', res.totalBytesSent)
        // console.log('预期需要上传的数据总长度', res.totalBytesExpectedToSend)
      });
    });
    return promise;
  },
  /**
   * 组件上传图片
   */
  mpUploadFile: function(files) {
    let promise = new Promise((resolve, reject) => {
      let urlsOriginal = [];
      let urls = [];
      files.tempFilePaths.forEach((item, index) => {
        let uploadTask = wx.uploadFile({
          url: this.globalData.url + this.globalData.urlImage,
          filePath: item,
          name: "file",
          header: {
            "Authorization": this.globalData.accessToken
          },
          formData: {
            savePath: "/applets/photo"
          },
          success: res => {
            urls.push(JSON.parse(res.data).data);
            if ((files.tempFilePaths.length - 1) == index) {
              resolve({
                urls: urls,
              })
            }
          },
          fail: res => {
            reject(res);
          },
          complete: res => {
            wx.hideLoading();
          }
        });
      })
    });
    return promise;
  },
  //选择单张或者多张图片  标签上需定义data-type(数据库图片字段)  data-number(选择图片数量) _fail(上传失败) _hidden(隐藏进度) _progress(进度多少)
  chooseImage: function(that, e) {
    wx.chooseImage({
      count: e.currentTarget.dataset.number,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: function(res) {
        let firstLength = res.tempFilePaths.length;
        let typeImg = e.currentTarget.dataset.type;
        if (e.currentTarget.dataset.number == 1) {
          var success = function(res) {
            if (JSON.parse(res.data).code == 1) { //根据项目修改code
              this.setData({
                ["obj." + "" + typeImg + ""]: [],
                ["obj." + "" + typeImg + ""]: [JSON.parse(res.data).data[0]]
              });
            } else {
              this.setData({
                ["obj." + "" + typeImg + "_fail"]: true,
              });
            }
          };
          let progressUpdate = function(res) {
            this.setData({
              ["obj." + "" + typeImg + "_hidden"]: true,
              ["obj." + "" + typeImg + "_progress"]: res.progress
            });
            if (res.progress >= 100) {
              this.setData({
                ["obj." + "" + typeImg + "_hidden"]: false,
              });
            }
          };
          this.uploadFile(res.tempFilePaths[0], success, progressUpdate);
        } else if (e.currentTarget.dataset.number > 1) {
          if ((firstLength + that.data.obj["" + typeImg + ""].length) <= e.currentTarget.dataset.number) {
            for (let i = 0; i < res.tempFilePaths.length; i++) {
              let success = function(res) {
                if (JSON.parse(res.data).code == 1) { //根据项目修改code
                  this.setData({
                    ["obj." + "" + typeImg + ""]: that.data.obj["" + typeImg + ""].concat(JSON.parse(res.data).data[0])
                  });
                } else {
                  this.setData({
                    ["obj." + "" + typeImg + "_fail"]: true
                  });
                }
              };
              let progressUpdate = function(res) {
                this.setData({
                  ["obj." + "" + typeImg + "_hidden"]: true,
                  ["obj." + "" + typeImg + "_progress"]: res.progress
                });
                if (res.progress >= 100) {
                  this.setData({
                    ["obj." + "" + typeImg + "_hidden"]: false,
                  });
                }
              };
              this.uploadFile(res.tempFilePaths[i], success, progressUpdate);
            }
          } else {
            wx.showToast({
              title: '最多' + e.currentTarget.dataset.number + '张',
            });
          }
        }
      }
    });
  },


  //删除图片 data-type
  deleteImage: function(that, e) {
    let typeImage = e.currentTarget.dataset.type;
    let index = that.data.obj["" + typeImage + ""].indexOf(e.currentTarget.id);
    if (index > -1) {
      that.data.obj["" + typeImage + ""].splice(index, 1);
    }
    that.setData({
      ["obj." + typeImage + ""]: that.data.obj["" + typeImage + ""]
    });
  },
  /**
   * 原生confirm框
   */
  confirm: function(title, content) {
    let promise = new Promise((resolve, reject) => {
      wx.showModal({
        title: title,
        content: content,
        confirmColor: this.globalData.theme.themeColor[0],
        success: function(res) {
          if (res.confirm) {
            resolve();
          } else {
            reject();
          }
        }
      });
    });
    return promise;
  },
  /**
   * 原生alert框
   */
  alert: function(title, content) {
    let promise = new Promise((resolve, reject) => {
      wx.showModal({
        title: title,
        content: content,
        showCancel: false,
        confirmColor: this.globalData.theme.themeColor[0],
        success: res => {
          resolve();
          if (res.confirm) {

          } else {

          }
        }
      });
    });
    return promise;
  },
  /**
   * 获取当前时间 2018-05-26 00:00:00
   */
  getNowFormatDate: function() {
    let date = new Date();
    let [year, month, day, hour, minute, second] = [date.getFullYear(), (date.getMonth() + 1),
      date.getDate(), date.getHours(), date.getMinutes(), date.getSeconds()
    ];
    if (month >= 1 && month <= 9) {
      month = "0" + month;
    }
    if (day >= 0 && day <= 9) {
      day = "0" + day;
    }
    if (hour >= 0 && hour <= 9) {
      hour = "0" + hour;
    }
    if (minute >= 0 && minute <= 9) {
      minute = "0" + minute;
    }
    if (second >= 0 && second <= 9) {
      second = "0" + second;
    }
    let currentDateTime = year + "-" + month + "-" + day + " " + hour + ":" + minute + ":" + second;
    return currentDateTime;
  },
  /**
   * 将经纬度转成地址
   * 
   */
  LonLatToAddress: function(longitude, latitude) {
    let promise = new Promise((resolve, reject) => {
      this.globalData.qqMapWx.reverseGeocoder({
        location: {
          latitude: latitude,
          longitude: longitude
        },
        success: res => {
          resolve(res);
        },
        fail: res => {
          reject(res);
        },
        complete: res => {
          wx.hideLoading();
          console.log(res);
        }
      });
    });
    return promise;
  },
  wxgetLocation: function() {

  },
  /**
   * 去除所有空格
   */
  removeAllSpace: function(currentValue) {
    if (!currentValue) {
      return "";
    }
    return currentValue.replace(/\s+/g, '');
  },
  /**
   * 判断是否已绑定小区
   */
  isBindCommunity: function() {
    let promise = new Promise((resolve, reject) => {
      this.wxGetRequest("/mine/getHouseByPeopleId", {
        people_id: this.globalData.userInfo["people_id"],
        page_number: 1,
        page_size: 10
      }).then(result => {
        if (!this.globalData.roomId) {
          result.data.data.list.forEach((item, index) => {
            if (index == 0) {
              this.globalData.roomId = item.room_id;
              this.globalData.yardId = item.yard_id;
              this.globalData.areaCode = item.area_code;
              wx.setStorageSync('roomId', item.room_id);
              wx.setStorageSync('yardId', item.yard_id);
              wx.setStorageSync('areaCode', item.area_code);
            }
          });
        }
        resolve(result);
      });
    });
    return promise;
  },
  /**
   * 点击判断是否已经登录和实名认证跳转页面
   */
  isVerifiedAuth: function(url) {
    let promise = new Promise((resolve, reject) => {
      if (this.globalData.userInfo["user_id"]) {
        if (this.globalData.userInfo["people_id"]) {
          if (!url) {
            resolve();
          } else {
            wx.navigateTo({
              url: url,
            })
          }
        } else {
          this.alert('提示', '请使用本人信息到【我的->入住登记】进行实名认证!');
        }
      } else {
        wx.navigateTo({
          url: '/pages/mine/login/login',
        })
      }
    });
    return promise;
  },
  /**
   * 判断是否已经登录跳转页面
   */
  isVerifiedLogin: function(url) {
    if (this.globalData.userInfo["user_id"]) {
      wx.navigateTo({
        url: url,
      })
    } else {
      wx.navigateTo({
        url: '/pages/mine/login/login',
      })
    }

  },
  /**
   * 获取用户信息
   */
  getUserInfo: function() {
    let promise = new Promise((resolve, reject) => {
      const accountInfo = wx.getAccountInfoSync();
      wx.login({
        success: res => {
          this.wxGetRequest("/mine/getWechatUser", {
            js_code: res.code,
            applet_id: accountInfo.miniProgram.appId,
          }).then(result => {
            console.error(result)
            this.globalData.userInfo = result.data.data;
            wx.setStorageSync('user_id', this.globalData.userInfo["user_id"]);
            wx.setStorageSync('people_id', this.globalData.userInfo["people_id"]);
            wx.setStorageSync('name', this.globalData.userInfo["name"]);
            this.isBindCommunity();
            resolve(result);
          });
        }
      })
    });
    return promise;
  },
  /**
   * 无需微信登录獲取用户信息
   */
  getWxUserInfo: function() {
    let promise = new Promise((resolve, reject) => {
      const accountInfo = wx.getAccountInfoSync();
      this.wxGetRequest("/wechart/mine/getUserInfo", {
        user_id: this.globalData.userInfo["user_id"]
      }).then(result => {
        this.globalData.wxUserInfo = result.data.data;
        resolve(result);
      });
    })
    return promise;
  },
  /**
   * 动态设置顶部的背景色
   */
  setNavigationBarColor: function() {
    wx.setNavigationBarTitle({
      title: this.globalData.appTitle,
    })
    wx.setNavigationBarColor({
      frontColor: '#00000',
      backgroundColor: '#ffffff',
    })
  },
  /**
   * 登记授权提交的院落是否申请成功
   */
  isYardApplySuccess: function() {
    let promise = new Promise((resolve, reject) => {
      this.wxGetRequest("/app-people/v1/room/apply/success", {
        people_id: this.globalData.userInfo["people_id"]
      }).then(result => {
        if (result.data.is_ok) {
          this.globalData.yardId = result.data.yard_id;
          resolve(result);
        } else {
          this.globalData.yardId = "";
        }
      });
    });
    return promise;
  },
  /**
   * 身份证加密
   */
  formatidcard: function(idcard) {
    if (idcard.length == 15) {
      return idcard.replace(/(\d{6})\d{6}(\d{3})/, "$1******$2");
    } else {
      return idcard.replace(/(\d{5})\d{6}(\d{6})/, "$1******$2");
    }
  },
  /**
   * 替换图片ip
   */
  formatImgIp: function(urlStr) {
    if (this.globalData.isReplaceImgIp) { //替换ip
      if (!urlStr) {
        return "";
      }
      let urlArray = urlStr.split(",");
      let urlNewArray = [];
      urlArray.forEach((item, index) => {
        // if (this.globalData.showImage == url[0]) {
        //   urlNewArray.push(this.globalData.originalImage + "files" + url[1]);
        // } else {
        //   urlNewArray.push(this.globalData.showImage + "files" + url[1]);
        // }
        if (item && item.indexOf("files") != -1) {
          let url = item.split("files");
          urlNewArray.push(this.globalData.showImage + "files" + url[1]);
        }
      });
      return urlNewArray;
      // if (urlStr && urlStr.indexOf("files") != -1) {
      //   let url = urlStr.split("files");
      //   // if (this.globalData.showImage != url[0]) {
      //   //   this.globalData.originalImage = url[0];
      //   // }


      //   return urlNewArray;
      // } else {
      //   return "";
      // }
    } else { //不替换ip
      if (!urlStr) {
        return "";
      }
      let urlArray = urlStr.split(",");
      return urlArray;
    }
  },
  /**
   * 日期加天数
   */
  addDayDate: function(date, days) {
    let d = new Date(date);
    d.setDate(d.getDate() + days);
    let m = d.getMonth() + 1;
    return d.getFullYear() + '-' + (m < 10 ? "0" + m : m) + '-' + (d.getDate() < 10 ? "0" + d.getDate() : d.getDate());
  },
})